﻿using System.Linq;
using System.Threading.Tasks;
using CRM.Extensions;
using CRM.Models;
using CRM.ViewModels.Email;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.AspNetCore.Identity;

namespace CRM.Controllers.Email
{
    [Route("api/[controller]")]
    [ApiController]
    public class EmailConfigGroupController : BaseController
    {
        private readonly MyDbContext _dbContext;
        private readonly UserManager<User> _userManager;

        public EmailConfigGroupController(MyDbContext dbContext, UserManager<User> userManager)
        {
            _dbContext = dbContext;
            _userManager = userManager;
        }

        [HttpGet(nameof(Index))]
        public async Task<ResultStruct> Index([FromQuery] string name)
        {
            var user = await _userManager.GetUserAsync(User);
            var result =
                await _dbContext.EmailConfigGroup
                    .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId &&
                                m.UserId == user.Id)
                    .WhenWhere(!string.IsNullOrEmpty(name), i => i.Name.StartsWith(name) || i.Name.EndsWith(name))
                    .ToPaginateAsync();
            return Success(result);
        }

        [HttpPost(nameof(Create))]
        public async Task<ResultStruct> Create(EmailConfigGroupVM vm)
        {
            var user = await _userManager.GetUserAsync(User);
            if (!ModelState.IsValid) return Error(message: ModelState.ToString());
            var result = await _dbContext.EmailConfigGroup
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId &&
                            m.UserId == user.Id).Where(m => m.Name == vm.Name).FirstOrDefaultAsync();

            if (result != null)
            {
                return Error(new object(), "当前分组名称已存在，请替换");
            }

            var model = vm.NewModel(user);
            await _dbContext.EmailConfigGroup.AddAsync(model);
            await _dbContext.SaveChangesAsync();
            return Success();
        }

        [HttpGet(nameof(GetGroupList))]
        public async Task<ResultStruct> GetGroupList()
        {
            var user = await _userManager.GetUserAsync(User);
            var result = await _dbContext.EmailConfigGroup
                .Where(m => m.OemId == user.OemId && m.CompanyId == user.CompanyId && m.GroupId == user.GroupId &&
                            m.UserId == user.Id).Select(m => new { label = m.Name, value = m.Id }).ToArrayAsync();
            return Success(result);
        }
    }
}